package com.wanshi.servlet;

import com.wanshi.entity.Product;
import com.wanshi.entity.User;
import com.wanshi.service.ProdService;
import com.wanshi.utils.Constants;
import com.wanshi.utils.DateUtils;
import com.wanshi.utils.PicUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@WebServlet("/seller/addProd")
public class addProd extends HttpServlet {

    private ProdService prodService = new ProdService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");


        ServletContext context = this.getServletContext();
        String picUrl = (String) context.getAttribute("pic_save_path");


        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        fileUpload.setFileSizeMax(1024*1024*5);

        Map<String,String> paramMap = new HashMap<>();
        try {
            List<FileItem> fileItems = fileUpload.parseRequest(request);

            for(FileItem item:fileItems){
                if(item.isFormField()){
                    //true  普通 还是文件上传
                    String name = item.getFieldName();
                    String value = item.getString("utf-8");
                    //单独处理爱好

                    paramMap.put(name,value);
                }else{
                    //文件上传  如何把图片保存到本地
                    //1 字节输出流, 把数据保存到本地的
                    String name = item.getName();
                    if(name == null || name.trim().equals("")){
                        paramMap.put("imgurl","");
                        continue;
                    }
                    String s = UUID.randomUUID().toString().replace("-","");
                    //获取文件名称后缀
                    int index = name.lastIndexOf('.');
                    String houzhui = name.substring(index);
                    String date = DateUtils.getFormatDate();  //    2021/11/02/
                    File file = new File(picUrl +date);
                    if(!file.exists()){
                        file.mkdirs();
                    }
                    File fileName = new File(file,s+houzhui);
                    FileOutputStream fos = new FileOutputStream(fileName);
                    //2 字节输入流, 读取前台提交数据的
                    InputStream is = item.getInputStream();
                    byte[] bs = new byte[1024];
                    int len = 0;
                    while( (len = is.read(bs)) != -1 ){
                        fos.write(bs,0,len);
                    }
                    is.close();
                    fos.close();

                    //对已经上传的文件进行压缩
                    PicUtils picUtils = new PicUtils(fileName.getAbsolutePath());
                    picUtils.resizeByWidth(200);
                    paramMap.put("imgurl",date+s+houzhui);
                }
            }
            Product prod = new Product();
            BeanUtils.copyProperties(prod,paramMap);

            HttpSession session = request.getSession();
            User user = (User) session.getAttribute("user");
            prod.setUser_id(user.getId());


            //2 添加到数据库
            prodService.addProd(prod);
                response.getWriter().write("添加成功!3秒后跳转到首页");
                response.setHeader("refresh","3;url="+request.getContextPath()+"/index.jsp");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

